'''
 # @ Author: Justin
 # @ Create Time: 2025-02-11 20:25:09
 # @ Modified by: Justin
 # @ Modified time: 2025-02-11 20:25:12
 # @ Description: 管理所有的聊天记录
 '''

from .messages import Messages
import os
import time

class MessagesManager:
    def __init__(self, dir : str = None) -> None:
        '''
        Args:
            dir (str, optional): 聊天记录的存储路径. 默认为None.
        '''
        
        self.dir = dir
        self.messages = [Messages]

        if self.dir is not None:
            # 从目录中加载聊天记录
            index = 0
            while True:
                filename = f'msg{index}.db'
                if not os.path.exists(os.path.join(self.dir, filename)):
                    break
                index += 1

                # 加载聊天记录
                self.messages.append(Messages(os.path.join(self.dir, filename)))

    def new_message(self, prompt : str = None) -> Messages:
        '''
        创建一个新的聊天记录
        Args:
            prompt (str, optional): 聊天记录的系统提示信息. 默认为None.
        Returns:
            Messages: 新的聊天记录
        '''

        if self.dir is not None:
            index = len(self.messages)
            filename = f'msg{index}.db'
            filepath = os.path.join(self.dir, filename)
            self.messages.append(Messages(filepath, prompt))
        else:
            self.messages.append(Messages(prompt=prompt))

        message = self.messages[-1]

        return message
    
    def get_messages_num(self) -> int:
        '''
        获取聊天记录的数量
        Returns:
            int: 聊天记录的数量
        '''

        return len(self.messages)

    def get_messages_by_index(self, index : int) -> Messages:
        '''
        根据索引获取聊天记录
        Args:
            index (int): 索引
        Returns:
            Messages: 聊天记录
        '''
        if index >= len(self.messages):
            return None
        
        return self.messages[index]
    
    def save_messages(self) -> None:
        '''
        保存所有聊天记录
        '''
        if self.dir is None:
            return
        
        for message in self.messages:
            message.save_message_to_db()

    def delete_massages_by_index(self, index : int) -> None:
        '''
        根据索引删除聊天记录
        Args:
            index (int): 索引
        '''
        if index >= len(self.messages):
            return
        
        message = self.messages[index]
        message.delete_self()
        self.messages.pop(index)
